<?php

namespace app\home\controller;

use think\Controller;
use think\Cookie;


//公共控制器
use app\common\controller\Home as HomeController;

/**
 * 评论控制器
 */
class Comment extends HomeController
{
    // 构造函数
    public function __construct()
    {
        //继承底层的控制器构造函数
        parent::__construct();

        //定义一个全局模型
        $this->PostModel = model('Post.Post');
        $this->UserModel = model('User.User');
        $this->RecordModel = model('User.Record');
        $this->CommentModel = model('Post.Comment');
    }

    //添加评论
    public function add()
    {
        if ($this->request->isPost()) {
            //获取帖子的id
            $postid = $this->request->param('postid', 0);

            //判断帖子是否存在
            $post = $this->PostModel->find($postid);

            if (!$post) {
                $this->error('帖子不存在');
                exit;
            }

            //评论的上级id
            $pid = $this->request->param('pid', 0);
            $comment = $this->CommentModel->find($pid);

            //根据上级pid去找评论
            if ($comment) {
                $level = $comment['level'] + 1;
            } else {
                //没有评论
                $level = 0;
            }

            //组装数据
            $data = [
                'pid' => $pid,
                'level' => $level,
                'content' => $this->request->param('content', ''),
                'userid' => $this->LoginUser['id'],
                'postid' => $post['id'],
                'accept' => 0
            ];

            //插入评论
            $result = $this->CommentModel->validate('common/Post/Comment')->save($data);

            if ($result === FALSE) {
                //插入失败
                $this->error($this->CommentModel->getError());
                exit;
            } else {
                //插入成功
                $this->success('评论成功', url('home/index/info', ['postid' => $post['id']]));
                exit;
            }
        }
    }

    //删除评论
    public function del()
    {
    }

    //采纳
    public function accept()
    {
        $success = [
            'result' => false,
            'msg' => ''
        ];

        if ($this->request->isPost()) {
            //评论id
            $comid = $this->request->param('comid', 0);

            //根据id去查询这个评论是否存在
            $comment = $this->CommentModel->with(['post', 'user'])->find($comid);

            if (!$comment) {
                //更新失败
                $success['result'] = false;
                $success['msg'] = '评论不存在，无法采纳';
                return json($success);
            }

            //当前评论是否已被采纳
            if ($comment['accept'] == 1) {
                //更新失败
                $success['result'] = false;
                $success['msg'] = '该评论已被采纳，无须重复采纳';
                return json($success);
            }

            if ($comment['post']['accept']) {
                //帖子已采纳
                $success['result'] = false;
                $success['msg'] = '帖子已完结';
                return json($success);
            }

            //采纳过程
            // 评论表 采纳字段 改成 1 已采纳
            // 帖子表 采纳人的字段  改成 指定用户id
            // 用户表 被采纳人的积分变化 
            // 被采纳人消费记录表  添加采纳的消费记录

            //开启事务
            $this->PostModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CommentModel->startTrans();


            //组装评论表数据
            $CommentData = [
                'id' => $comid,
                'accept' => 1
            ];

            //更新评论表
            $CommentStatus = $this->CommentModel->isUpdate(true)->save($CommentData);

            if ($CommentStatus === FALSE) {
                //更新失败
                $success['result'] = false;
                $success['msg'] = $this->CommentModel->getError();
                return json($success);
            }

            //帖子表
            $PostData = [
                'id' => $comment['postid'],
                'accept' => $comment['userid'],
            ];

            //更新帖子表
            $PostStatus = $this->PostModel->isUpdate(true)->save($PostData);

            if ($PostStatus === FALSE) {
                //更新失败
                $this->CommentModel->rollback();

                $success['result'] = false;
                $success['msg'] = $this->PostModel->getError();
                return json($success);
            }


            //更新用户表的积分字段
            $UserPoint = $comment['user']['point']; //用户积分
            $PostPoint = $comment['post']['point'];  //悬赏积分

            $UpdatePoint = bcadd($UserPoint, $PostPoint);

            //组装用户更新数据
            $UserData = [
                'id' => $comment['userid'],
                'point' => $UpdatePoint
            ];

            //更新用户表
            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

            if ($UserStatus === FALSE) {
                //更新失败
                $this->PostModel->rollback();
                $this->CommentModel->rollback();

                $success['result'] = false;
                $success['msg'] = $this->UserModel->getError();
                return json($success);
            }

            //组装消费记录的数据
            $RecordData = [
                'point' => $PostPoint,
                'state' => 2,
                'userid' => $comment['userid'],
                'content' => "【" . $comment['post']['title'] . "】获得采纳积分:<b>" . $PostPoint . "积分</b> 采纳时间：" . date("Y-m-d H:i")
            ];

            $RecordStatus = $this->RecordModel->save($RecordData);

            if ($RecordStatus === FALSE) {
                //插入消费记录失败
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->CommentModel->rollback();

                $success['result'] = false;
                $success['msg'] = $this->RecordModel->getError();
                return json($success);
            }

            //最终判断
            if ($CommentStatus === FALSE || $PostStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE) {
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->CommentModel->rollback();
                $this->RecordModel->rollback();
                $success['result'] = false;
                $success['msg'] = '采纳失败，请重新选择';
                return json($success);
            } else {
                //提交事务
                $this->UserModel->commit();
                $this->PostModel->commit();
                $this->CommentModel->commit();
                $this->RecordModel->commit();
                $success['result'] = true;
                $success['msg'] = '采纳成功，帖子完结';
                return json($success);
            }
        }
    }
}
